<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI家居设计助手 - 灵犀智苑</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script>
        // DeepSeek API配置
        const DEEPSEEK_API_KEY = "sk-ad3be42802c2411ba8a1f550dbba97e2"; // 替换为你的DeepSeek API Key
        const DEEPSEEK_API_URL = "https://api.deepseek.com/chat/completions";
        // 后端API基础地址
        const API_BASE_URL = "http://localhost:8088/another"; 
    </script>
    <style>
        /* ... （CSS样式保持不变） ... */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }

        :root {
            --primary: #4361ee;
            --primary-light: #5e72e4;
            --secondary: #4cc9f0;
            --accent: #e67e22;
            --light: #ecf0f1;
            --dark: #34495e;
            --darker: #2c3e50;
            --success: #27ae60;
            --danger: #e74c3c;
            --text: #2c3e50;
            --text-light: #7f8c8d;
            --glass: rgba(255, 255, 255, 0.2);
            --border: rgba(255, 255, 255, 0.3);
            --shadow: 0 8px 32px rgba(31, 38, 135, 0.15);
            --transition: all 0.3s ease;
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
            color: var(--text);
            min-height: 100vh;
            overflow-x: hidden;
        }

        .background-blur {
            position: fixed;
            top: -50px;
            left: -50px;
            right: -50px;
            bottom: -50px;
            background: url('');
            filter: blur(40px);
            z-index: -1;
        }

        /* 玻璃拟态效果 */
        .glass {
            background: var(--glass);
            backdrop-filter: blur(12px);
            -webkit-backdrop-filter: blur(12px);
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
            border-radius: 20px;
            overflow: hidden;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 2rem;
        }

        /* 导航栏样式 */
        header {
            padding: 1rem 0;
        }

        .navbar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem 2rem;
            position: relative;
            z-index: 100;
        }

        .logo {
            display: flex;
            align-items: center;
            font-size: 1.8rem;
            font-weight: 700;
            background: linear-gradient(90deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .logo-icon {
            margin-right: 10px;
            animation: float 3s ease-in-out infinite;
        }

        .nav-links {
            list-style: none;
            display: flex;
            gap: 2rem;
        }

        .nav-links a {
            color: var(--darker);
            text-decoration: none;
            font-weight: 500;
            padding: 8px 0;
            position: relative;
            transition: var(--transition);
        }

        .nav-links a:after {
            content: '';
            position: absolute;
            width: 0;
            height: 2px;
            bottom: 0;
            left: 0;
            background: var(--primary);
            transition: var(--transition);
        }

        .nav-links a:hover:after,
        .nav-links a.active:after {
            width: 100%;
        }

        .nav-links a.active {
            color: var(--primary);
        }

        .cta-buttons {
            display: flex;
            gap: 1rem;
        }

        .btn {
            padding: 0.7rem 1.5rem;
            border-radius: 12px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }

        .btn-login {
            background: transparent;
            color: var(--darker);
            border: 1px solid var(--border);
        }

        .btn-login:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-2px);
        }

        .btn-signup {
            background: linear-gradient(90deg, var(--primary), var(--secondary));
            color: white;
            box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
        }

        .btn-signup:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
        }

        /* 主内容区域 */
        main {
            padding: 4rem 0;
        }

        .hero {
            padding: 3rem;
            margin-bottom: 2rem;
            text-align: center;
        }

        .hero-content {
            max-width: 800px;
            margin: 0 auto;
        }

        .hero h1 {
            font-size: 3.5rem;
            font-weight: 700;
            margin-bottom: 1.5rem;
            background: linear-gradient(90deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .subtitle {
            font-size: 1.4rem;
            font-weight: 300;
            margin-bottom: 2.5rem;
            color: #4a5568;
        }

        .section-title {
            text-align: center;
            margin-bottom: 40px;
        }

        .section-title h2 {
            font-size: 2.5rem;
            margin-bottom: 15px;
            position: relative;
            display: inline-block;
            background: linear-gradient(90deg, var(--primary), var(--accent));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .section-title h2::after {
            content: '';
            position: absolute;
            bottom: -10px;
            left: 50%;
            transform: translateX(-50%);
            width: 80px;
            height: 4px;
            background: var(--accent);
            border-radius: 2px;
        }

        .section-title p {
            font-size: 1.2rem;
            color: var(--text-light);
            max-width: 700px;
            margin: 0 auto;
        }

        /* AI设计区域 */
        .ai-design-container {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 40px;
            margin-bottom: 60px;
        }

        .design-input {
            border-radius: 20px;
            padding: 30px;
            display: flex;
            flex-direction: column;
        }

        .design-input h3 {
            font-size: 1.8rem;
            margin-bottom: 20px;
            color: var(--primary);
        }

        .design-input p {
            color: var(--text-light);
            margin-bottom: 25px;
        }

        .input-group {
            margin-bottom: 25px;
        }

        .input-group label {
            display: block;
            margin-bottom: 10px;
            font-weight: 500;
            color: var(--darker);
        }

        .input-group input, 
        .input-group textarea,
        .input-group select {
            width: 100%;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 12px;
            font-size: 1rem;
            background: rgba(255, 255, 255, 0.5);
            transition: var(--transition);
        }

        .input-group input:focus, 
        .input-group textarea:focus, 
        .input-group select:focus {
            outline: none;
            border-color: var(--secondary);
            box-shadow: 0 0 0 3px rgba(76, 201, 240, 0.2);
        }

        .input-group textarea {
            height: 150px;
            resize: vertical;
        }

        .style-options {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
            margin-bottom: 25px;
        }

        .style-option {
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 12px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: var(--transition);
            background: rgba(255, 255, 255, 0.15);
        }

        .style-option:hover, .style-option.active {
            border-color: var(--secondary);
            background-color: rgba(76, 201, 240, 0.2);
        }

        .style-option i {
            font-size: 2.5rem;
            color: var(--secondary);
            margin-bottom: 10px;
        }

        .design-output {
            border-radius: 20px;
            padding: 30px;
            display: flex;
            flex-direction: column;
        }

        .output-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.3);
        }

        .output-header h3 {
            font-size: 1.8rem;
            color: var(--primary);
        }

        .output-actions {
            display: flex;
            gap: 10px;
        }

        .output-content {
            flex: 1;
            display: flex;
            flex-direction: column;
            gap: 25px;
        }

        .ai-recommendation {
            background: rgba(249, 249, 249, 0.2);
            border-radius: 16px;
            padding: 25px;
            max-height: 500px;
            overflow-y: auto;
        }

        .ai-recommendation h4 {
            font-size: 1.4rem;
            margin-bottom: 15px;
            color: var(--darker);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .ai-recommendation h4 i {
            color: var(--accent);
        }

        .recommendation-content {
            line-height: 1.8;
        }

        .recommendation-content p {
            margin-bottom: 15px;
        }

        .recommendation-list {
            padding-left: 20px;
            margin: 15px 0;
        }

        .recommendation-list li {
            margin-bottom: 10px;
            position: relative;
            padding-left: 20px;
        }

        .recommendation-list li:before {
            content: "•";
            position: absolute;
            left: 0;
            color: var(--primary);
            font-size: 1.2rem;
        }

        .generate-btn {
            width: 100%;
            padding: 16px;
            font-size: 1.2rem;
            font-weight: 600;
            margin-top: 20px;
            background: linear-gradient(90deg, var(--primary), var(--accent));
            color: white;
            border: none;
            border-radius: 12px;
            cursor: pointer;
            transition: var(--transition);
            box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
        }

        .generate-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
        }

        .generate-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        /* 加载状态 */
        .ai-loading {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            gap: 20px;
            padding: 30px;
            display: none;
        }
        
        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 5px solid rgba(76, 201, 240, 0.3);
            border-top: 5px solid var(--primary);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .ai-typing {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 12px;
            margin-top: 15px;
            display: none;
        }
        
        .typing-dots {
            display: flex;
            gap: 5px;
        }
        
        .typing-dot {
            width: 8px;
            height: 8px;
            background-color: var(--primary);
            border-radius: 50%;
            opacity: 0.5;
            animation: pulse 1.5s infinite;
        }
        
        .typing-dot:nth-child(2) {
            animation-delay: 0.5s;
        }
        
        .typing-dot:nth-child(3) {
            animation-delay: 1s;
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 0.5; transform: scale(1); }
            50% { opacity: 1; transform: scale(1.1); }
        }
        
        /* 动画 */
        @keyframes float {
            0% {
                transform: translateY(0px);
            }
            50% {
                transform: translateY(-15px);
            }
            100% {
                transform: translateY(0px);
            }
        }

        /* 新增图片显示样式 */
        .image-output {
            margin-top: 20px;
            text-align: center;
            min-height: 200px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            background: rgba(249, 249, 249, 0.2);
            border-radius: 16px;
            padding: 25px;
            border: 1px dashed var(--border);
            color: var(--text-light);
        }

        .image-output img {
            max-width: 100%;
            height: auto;
            border-radius: 12px;
            box-shadow: var(--shadow);
            margin-top: 15px;
            display: none; /* 默认隐藏 */
        }

        .image-output .loading-spinner {
            margin-top: 20px;
            display: none; /* 默认隐藏 */
        }

        /* 新增：热门套餐推荐区域样式 */
        .recommended-packages {
            padding: 4rem 0;
            margin-top: 40px;
        }

        .package-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 30px;
            margin-top: 30px;
            min-height: 250px; /* 确保有足够高度显示加载动画 */
            align-items: center;
            justify-content: center;
        }

        .package-card {
            background: var(--glass);
            backdrop-filter: blur(10px);
            -webkit-backdrop-filter: blur(10px);
            border: 1px solid var(--border);
            box-shadow: var(--shadow);
            border-radius: 15px;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            transition: var(--transition);
            cursor: pointer;
        }

        .package-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(31, 38, 135, 0.2);
        }

        .package-image-container {
            width: 100%;
            height: 200px;
            overflow: hidden;
            border-bottom: 1px solid var(--border);
        }

        .package-image {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
        }

        .package-card:hover .package-image {
            transform: scale(1.05);
        }

        .package-info {
            padding: 20px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .package-info h4 {
            font-size: 1.5rem;
            color: var(--darker);
            margin-bottom: 10px;
            line-height: 1.3;
        }

        .package-description {
            font-size: 0.95rem;
            color: var(--text-light);
            margin-bottom: 15px;
            flex-grow: 1;
        }

        .package-price {
            font-size: 1.6rem;
            font-weight: 700;
            color: var(--primary);
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 10px;
        }

        .package-price span {
            font-size: 1.1rem;
            color: var(--accent);
            margin-left: 5px;
        }

        .view-details-btn {
            background: var(--primary);
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 8px;
            font-size: 0.9rem;
            cursor: pointer;
            transition: var(--transition);
        }

        .view-details-btn:hover {
            background: var(--primary-light);
            transform: translateY(-2px);
        }

        /* 推荐套餐加载动画居中 */
        #recommendation-loading {
            grid-column: 1 / -1; /* 占据所有列 */
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 50px 0;
        }

        /* 响应式设计 */
        @media (max-width: 1024px) {
            .ai-design-container {
                grid-template-columns: 1fr;
            }
            
            .hero h1 {
                font-size: 3rem;
            }
        }

        @media (max-width: 768px) {
            .navbar {
                flex-direction: column;
                gap: 1.5rem;
            }
            
            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
            
            .hero h1 {
                font-size: 2.2rem;
            }
            
            .hero p {
                font-size: 1.1rem;
            }
            
            .section-title h2 {
                font-size: 2rem;
            }
            
            .style-options {
                grid-template-columns: 1fr;
            }
            
            .output-actions {
                flex-direction: column;
            }
        }

        @media (max-width: 480px) {
            .hero h1 {
                font-size: 1.8rem;
            }
            
            .section-title h2 {
                font-size: 1.8rem;
            }
        }
    </style>
</head>
<body>
    <div class="background-blur"></div>
    
    <header>
        <nav class="navbar glass">
            <div class="logo">
                <span class="logo-icon">✨</span>
                <span>灵犀智苑</span>
            </div>
            <ul class="nav-links">
                <li><a href="index.html">首页</a></li>
                <li><a href="#" class="active">AI设计</a></li>
                <li><a href="mall.html">家具商城</a></li>
                <li><a href="idea.html">灵感库</a></li>
                <li><a href="partner.html">商家合作</a></li>
            </ul>
            <div class="cta-buttons">
                <a href="login.html" class="btn btn-login glass">登录</a>
                <a href="register.html" class="btn btn-signup">免费注册</a>
            </div>
        </nav>
    </header>
    
    <main class="container">
        <section class="hero glass">
            <div class="hero-content">
                <h1>AI智能家居设计助手</h1>
                <p class="subtitle">输入您的家居需求，获取专业的家具购买建议</p>
            </div>
        </section>
        
        <section class="ai-design">
            <div class="section-title">
                <h2>家居设计需求</h2>
                <p>描述您的空间与风格偏好，AI将提供专业建议</p>
            </div>
            
            <div class="ai-design-container">
                <div class="design-input glass">
                    <h3>输入您的需求</h3>
                    <p>请提供尽可能详细的信息以获得更准确的建议</p>
                    
                    <div class="input-group">
                        <label for="room-type">空间类型</label>
                        <select id="room-type">
                            <option value="客厅">客厅</option>
                            <option value="卧室">卧室</option>
                            <option value="厨房">厨房</option>
                            <option value="餐厅">餐厅</option>
                            <option value="书房">书房</option>
                            <option value="阳台">阳台</option>
                            <option value="儿童房">儿童房</option>
                        </select>
                    </div>
                    
                    <div class="input-group">
                        <label for="room-size">空间尺寸（平方米）</label>
                        <input type="number" id="room-size" min="5" max="100" value="20">
                    </div>
                    
                    <div class="input-group">
                        <label for="budget">预算范围</label>
                        <select id="budget">
                            <option value="经济型（1万以下）">经济型（1-10k）</option>
                            <option value="中等预算（1-3万）">中等预算（10-30k）</option>
                            <option value="高端定制（3万以上）">高端定制（30k+）</option>
                        </select>
                    </div>
                    
                    <div class="input-group">
                        <label>设计风格</label>
                        <div class="style-options">
                            <div class="style-option active" data-value="现代简约">
                                <i class="fas fa-palette"></i>
                                <div>现代简约</div>
                            </div>
                            <div class="style-option" data-value="北欧风">
                                <i class="fas fa-leaf"></i>
                                <div>北欧风</div>
                            </div>
                            <div class="style-option" data-value="轻奢风">
                                <i class="fas fa-gem"></i>
                                <div>轻奢风</div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="input-group">
                        <label for="additional-info">额外需求</label>
                        <textarea id="additional-info" placeholder="例如：需要更多储物空间、有小孩需要安全设计、喜欢自然采光..."></textarea>
                    </div>
                    
                    <button class="generate-btn" id="generate-btn">
                        <i class="fas fa-bolt"></i> 生成设计方案
                    </button>
                    
                    <div class="ai-loading" id="ai-loading">
                        <div class="loading-spinner"></div>
                        <p>AI正在为您生成专业建议，请稍候...</p>
                    </div>
                </div>
                
                <div class="design-output glass">
                    <div class="output-header">
                        <h3>AI设计方案</h3>
                        <div class="output-actions">
                            <button class="btn btn-login glass" id="save-btn">
                                <i class="fas fa-download"></i> 保存
                            </button>
                            <button class="btn btn-signup" id="regenerate-btn">
                                <i class="fas fa-sync-alt"></i> 重新生成
                            </button>
                        </div>
                    </div>
                    
                    <div class="output-content">
                        <div class="ai-recommendation">
                            <h4><i class="fas fa-lightbulb"></i> AI家居购买建议</h4>
                            <div class="ai-typing" id="typing-indicator">
                                <span>AI正在思考...</span>
                                <div class="typing-dots">
                                    <div class="typing-dot"></div>
                                    <div class="typing-dot"></div>
                                    <div class="typing-dot"></div>
                                </div>
                            </div>
                            <div id="ai-response" class="recommendation-content">
                                <p>请填写左侧信息并点击"生成设计方案"按钮，AI将为您提供专业的家具购买建议。</p>
                                <p>建议将包含：</p>
                                <ul class="recommendation-list">
                                    <li>推荐的家具类型和数量</li>
                                    <li>材质和颜色搭配建议</li>
                                    <li>空间布局方案</li>
                                    <li>预算分配建议</li>
                                    <li>品牌和采购建议</li>
                                </ul>
                            </div>
                        </div>
                        
                        <div class="chat-actions" style="margin-top: 20px; display: flex; gap: 10px;">
                            <button id="summarizeAdviceBtn" class="btn btn-login glass" style="flex: 1;">
                                <i class="fas fa-tags"></i> 总结关键词
                            </button>
                            <button id="generateImageBtn" class="btn btn-signup" style="flex: 1;">
                                <i class="fas fa-image"></i> 生成图片
                            </button>
                        </div>

                        <div class="ai-response-container" style="margin-top: 20px;">
                            <h3>总结关键词：</h3>
                            <div id="keywordSummary" class="ai-response-box glass" style="padding: 15px; min-height: 50px; display: flex; align-items: center;">
                                暂无总结
                            </div>
                        </div>

                        <div class="ai-response-container" style="margin-top: 20px;">
                            <h3>AI效果图：</h3>
                            <div id="imageOutput" class="image-output glass">
                                <p id="imagePlaceholder">图片将在此处显示</p>
                                <img id="generatedImage" src="" alt="生成的AI效果图">
                                <div class="loading-spinner" id="imageLoadingSpinner"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
        
        <section class="recommended-packages">
            <div class="section-title">
                <h2>热门套餐推荐</h2>
                <p>根据您的喜好，精选优质家居套餐</p>
            </div>
            <div class="package-grid" id="package-grid">
                <div class="ai-loading" id="recommendation-loading" style="display: flex;">
                    <div class="loading-spinner"></div>
                    <p>正在加载热门套餐，请稍候...</p>
                </div>
            </div>
            <div style="text-align: center; margin-top: 30px;">
                <button class="btn btn-signup" id="refresh-recommendations-btn">
                    <i class="fas fa-sync-alt"></i> 换一换
                </button>
            </div>
        </section>

    </main>
    
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // 获取DOM元素
        const roomType = document.getElementById('room-type');
        const roomSize = document.getElementById('room-size');
        const budget = document.getElementById('budget');
        const additionalInfo = document.getElementById('additional-info');
        const generateBtn = document.getElementById('generate-btn');
        const regenerateBtn = document.getElementById('regenerate-btn');
        const saveBtn = document.getElementById('save-btn');
        const aiResponse = document.getElementById('ai-response');
        const styleOptions = document.querySelectorAll('.style-option');
        const aiLoading = document.getElementById('ai-loading');
        const typingIndicator = document.getElementById('typing-indicator');
        
        // 新增变量获取
        const summarizeAdviceBtn = document.getElementById('summarizeAdviceBtn');
        const keywordSummary = document.getElementById('keywordSummary');
        const generateImageBtn = document.getElementById('generateImageBtn'); 
        const imageOutput = document.getElementById('imageOutput'); 
        const generatedImage = document.getElementById('generatedImage'); 
        const imagePlaceholder = document.getElementById('imagePlaceholder'); 
        const imageLoadingSpinner = document.getElementById('imageLoadingSpinner'); 

        // 推荐套餐相关DOM元素
        const packageGrid = document.getElementById('package-grid');
        const recommendationLoading = document.getElementById('recommendation-loading');
        const refreshRecommendationsBtn = document.getElementById('refresh-recommendations-btn');
        
        // 当前选择的风格
        let selectedStyle = '现代简约';
        
        // 用于存储最近一次AI生成的完整建议
        let lastGeneratedAIDesignAdvice = ''; 

        // 风格选择处理
        styleOptions.forEach(option => {
            option.addEventListener('click', function() {
                // 移除同组的active状态
                const parent = this.parentElement;
                parent.querySelectorAll('.style-option').forEach(el => {
                    el.classList.remove('active');
                });
                
                // 设置当前为active
                this.classList.add('active');
                
                // 更新选择的风格
                selectedStyle = this.dataset.value;
            });
        });
        
        // 调用DeepSeek API函数
        async function fetchDeepSeekAPI(prompt) {
            const response = await fetch(DEEPSEEK_API_URL, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${DEEPSEEK_API_KEY}`
                },
                body: JSON.stringify({
                    model: "deepseek-chat",
                    messages: [
                        {
                            role: "system",
                            content: "你是一位经验丰富的家居设计师，擅长将客户需求转化为实用美观的设计方案。请提供专业、详细且易于理解的建议。"
                        },
                        {
                            role: "user",
                            content: prompt
                        }
                    ],
                    temperature: 0.7,
                    max_tokens: 1500,
                    stream: false
                })
            });
            
            if (!response.ok) {
                throw new Error(`API错误: ${response.status}`);
            }
            
            const data = await response.json();
            return data.choices[0].message.content;
        }
        
        // 显示AI响应函数
        function displayAIResponse(response) {
            // 尝试解析HTML格式的响应
            try {
                // 创建临时容器
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = response;
                
                // 如果响应包含列表结构，进行美化
                const lists = tempDiv.querySelectorAll('ul, ol');
                lists.forEach(list => {
                    list.classList.add('recommendation-list');
                });
                
                aiResponse.innerHTML = tempDiv.innerHTML;
                
            } catch (e) {
                // 如果无法解析为HTML，作为纯文本显示
                aiResponse.innerHTML = `<p>${response}</p>`;
            }
        }

        // 总结AI建议为关键词函数
        async function summarizeAIAdvice() {
            const adviceContent = aiResponse.innerHTML;
            if (!adviceContent || adviceContent.trim() === '暂无设计建议' || adviceContent.trim() === '正在生成建议中...' || adviceContent.trim().includes('请填写左侧信息')) {
                alert('请先生成家居设计建议，然后才能进行总结！');
                return;
            }

            keywordSummary.innerHTML = '正在总结中...'; 
            summarizeAdviceBtn.disabled = true; 
            generateImageBtn.disabled = true; // 总结中，禁用图片生成按钮

            const prompt = `作为专业室内设计师，请从以下家居设计建议中提取不超过10个核心视觉元素相关的中文关键词，这些关键词应直接适用于AI绘图工具生成效果图。请以英文逗号分隔这些关键词，不要包含任何额外的文字或解释。例如："现代简约客厅,绿色盆栽,自然采光,木质家具,暖色调灯光"\n\n家居设计建议内容:\n${adviceContent}`;

            try {
                const summary = await fetchDeepSeekAPI(prompt); 
                keywordSummary.innerHTML = summary; 
            } catch (error) {
                console.error('总结关键词失败:', error);
                keywordSummary.innerHTML = '总结失败，请重试。';
                alert('总结关键词失败');
            } finally {
                summarizeAdviceBtn.disabled = false; 
                generateImageBtn.disabled = false; // 总结完成，启用图片生成按钮
            }
        }

        // 生成图片功能
        async function generateImage() {
            const keywords = keywordSummary.innerText.trim();
            if (!keywords || keywords === '暂无总结' || keywords === '正在总结中...' || keywords.includes('总结失败')) {
                alert('请先总结关键词，然后才能生成图片！');
                return;
            }

            imagePlaceholder.style.display = 'none';
            generatedImage.style.display = 'none';
            imageLoadingSpinner.style.display = 'block'; // 显示加载动画
            generateImageBtn.disabled = true; // 禁用按钮

            try {
                // 构建图片生成接口URL，text作为query参数
                const requestUrl = `${API_BASE_URL}/user/ai/text2img?text=${encodeURIComponent(keywords)}`;
                
                // 发起POST请求获取图片URL字符串
                const response = await fetch(requestUrl, {
                    method: 'POST',
                    // 注意：如果后端需要认证或其他header，请在此处添加
                    // headers: {
                    //     'Authorization': `Bearer YOUR_TOKEN`,
                    //     'Content-Type': 'application/json' // 如果有body，可以加上
                    // },
                    // body: JSON.stringify({}) // 如果POST请求需要空body或者其他JSON数据，可以加上
                });

                // 检查HTTP响应状态码
                if (!response.ok) {
                    const errorText = await response.text();
                    console.error('图片API返回错误状态码:', response.status, errorText);
                    throw new Error(`图片API错误: ${response.status} - ${errorText}`);
                }

                let imageUrl = await response.text(); // 获取响应体中的URL字符串
                imageUrl = imageUrl.trim().replace(/^"|"$/g, ''); 
                // alert('请求URL:\n' + imageUrl);
                // 新增：验证后端返回的URL格式
                if (!imageUrl) {
                    console.error('后端返回的图片URL格式为空:', imageUrl);
                    throw new Error('后端返回的图片URL格式为空，请检查后端或联系管理员。');
                } else if (typeof imageUrl !== 'string') {
                    console.error('后端返回的图片URL数据类型不正确:', imageUrl);
                    throw new Error('后端返回的图片URL数据类型不正确，请检查后端或联系管理员。');
                } else if (!imageUrl.startsWith('http')) {
                    console.error('后端返回的图片URL格式错误:', imageUrl);
                    throw new Error('后端返回的图片URL格式错误，请检查后端或联系管理员。');
                }

                generatedImage.src = imageUrl; // 设置图片src为接收到的URL
                
                // 确保图片加载成功后显示
                generatedImage.onload = () => {
                    imageLoadingSpinner.style.display = 'none'; // 隐藏加载动画
                    generatedImage.style.display = 'block'; // 显示图片
                    // 注意：这里不需要URL.revokeObjectURL，因为URL是后端提供的远程URL
                };

                // 处理图片加载失败的情况（例如OSS上的图片不存在或加载失败）
                generatedImage.onerror = () => {
                    imageLoadingSpinner.style.display = 'none';
                    imagePlaceholder.style.display = 'block';
                    imagePlaceholder.innerText = '图片加载失败，请检查URL是否有效或网络。'; // 更具体的错误提示
                    alert('图片加载失败，请检查URL或网络。');
                };

            } catch (error) {
                console.error('生成图片失败:', error); // 打印详细错误信息
                imageLoadingSpinner.style.display = 'none';
                imagePlaceholder.style.display = 'block';
                // 根据错误类型显示不同提示
                if (error.message.includes('CORS') || error.message.includes('Failed to fetch')) {
                     imagePlaceholder.innerText = `网络或跨域配置错误：${error.message}，请检查后端CORS。`;
                } else if (error.message.includes('图片API错误')) {
                     imagePlaceholder.innerText = `后端API返回错误：${error.message}`;
                } else {
                     imagePlaceholder.innerText = `图片生成失败：${error.message}`;
                }
                alert('生成图片失败'); // 仍然弹出统一提示
            } finally {
                generateImageBtn.disabled = false; // 重新启用按钮
            }
        }
        
        // 生成设计方案按钮的事件监听器
        generateBtn.addEventListener('click', async function() {
            const room = roomType.value;
            const size = roomSize.value;
            const budgetValue = budget.value;
            const additional = additionalInfo.value.trim();
            
            // 验证输入
            if (!size || size < 5 || size > 100) {
                alert('请输入有效的房间尺寸（5-100平方米）');
                return;
            }
            
            // 显示加载状态
            generateBtn.disabled = true;
            aiLoading.style.display = 'flex';
            typingIndicator.style.display = 'flex';
            aiResponse.innerHTML = '';
            // 清空之前的总结结果和图片，因为建议内容会更新
            keywordSummary.innerHTML = '暂无总结'; 
            imagePlaceholder.style.display = 'block';
            imagePlaceholder.innerText = '图片将在此处显示';
            generatedImage.style.display = 'none';
            generatedImage.src = ''; // 清空图片src
            
            try {
                // 构造提示词
                const prompt = `作为专业家居设计师，请为${room}（${size}平方米）提供家具购买建议。
要求：
- 风格：${selectedStyle}
- 预算：${budgetValue}
- 额外需求：${additional || '无'}
请提供：
1. 核心家具清单（带推荐尺寸）
2. 材质和颜色搭配建议
3. 空间布局方案
4. 预算分配建议
5. 品牌和采购建议
请使用专业但易懂的语言，并给出具体实施建议。`;
                
                // 调用DeepSeek API
                const responseContent = await fetchDeepSeekAPI(prompt);
                lastGeneratedAIDesignAdvice = responseContent; // 保存完整的AI建议
                
                // 显示AI响应
                displayAIResponse(responseContent);

                // 根据AI设计方案生成热门套餐
                await fetchRecommendedPackages(lastGeneratedAIDesignAdvice);
                
            } catch (error) {
                console.error('API调用失败:', error);
                aiResponse.innerHTML = `<p class="error">获取AI建议失败，请稍后重试：${error.message}</p>`;
            } finally {
                // 隐藏加载状态
                aiLoading.style.display = 'none';
                typingIndicator.style.display = 'none';
                generateBtn.disabled = false;
            }
        });
        
        // 重新生成按钮的事件监听器
        regenerateBtn.addEventListener('click', function() {
            generateBtn.click();
        });
        
        // 保存功能按钮的事件监听器
        saveBtn.addEventListener('click', function() {
            const content = aiResponse.innerHTML;
            if (!content || content.includes('请填写左侧信息')) {
                alert('请先生成设计方案');
                return;
            }
            
            // 创建下载链接
            const blob = new Blob([content], { type: 'text/html' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `灵犀智苑-家居设计方案-${new Date().toLocaleDateString()}.html`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            alert('设计方案已保存！');
        });
        
        // 事件监听器：点击总结关键词按钮
        if (summarizeAdviceBtn) {
            summarizeAdviceBtn.addEventListener('click', summarizeAIAdvice);
        }

        // 事件监听器：点击生成图片按钮
        if (generateImageBtn) {
            generateImageBtn.addEventListener('click', generateImage);
        }

        // --- 新增：推荐套餐相关JavaScript代码 ---
        // 传入aiAdvice参数，如果存在则用于推荐；否则进行随机推荐
        async function fetchRecommendedPackages(aiAdvice = null) {
            packageGrid.innerHTML = ''; // 清空现有内容
            recommendationLoading.style.display = 'flex'; // 显示加载动画
            refreshRecommendationsBtn.disabled = true; // 禁用按钮

            let requestBody = {};
            let method = 'GET';
            let url = `${API_BASE_URL}/user/ai/recommend?count=3`;
			/*
            if (aiAdvice) {
                // 如果有AI建议，则发送POST请求并带上建议内容
                method = 'POST';
                url = `${API_BASE_URL}/user/ai/recommend`; // 假设后端有一个新的接口处理AI建议
                requestBody = {
                    advice: aiAdvice,
                    count: 3
                };
            }
			*/

            try {
                const fetchOptions = {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };

                if (method === 'POST') {
                    fetchOptions.body = JSON.stringify(requestBody);
                }
                
                const response = await fetch(url, fetchOptions);

                if (!response.ok) {
                    const errorText = await response.text();
                    throw new Error(`API错误: ${response.status} - ${errorText}`);
                }

                const result = await response.json(); // 假设后端返回 {code: 1, msg: "success", data: [...]}

                if (result.code === 1 && result.data && result.data.length > 0) {
                    recommendationLoading.style.display = 'none'; // 隐藏加载动画
                    result.data.forEach(setmenu => {
						console.log(setmenu.description);
						// alert(`当前套餐图片URL: ${setmenu.image}`);
                        const packageCard = document.createElement('div');
                        packageCard.classList.add('package-card');
                        packageCard.innerHTML = `
                            <div class="package-image-container">
                                <img src="${setmenu.image || 'https://via.placeholder.com/300x200?text=No+Image'}" alt="${setmenu.name}" class="package-image">
                            </div>
                            <div class="package-info">
                                <h4>${setmenu.name}</h4>
                                <p class="package-description">${setmenu.description || '暂无详细描述。'}</p>
                                <div class="package-price">
                                    <span>¥${setmenu.price ? setmenu.price.toFixed(2) : 'N/A'}</span>
                                    <button class="view-details-btn">查看详情</button>
                                </div>
                            </div>
                        `;
                        packageGrid.appendChild(packageCard);
                    });
                } else {
                    recommendationLoading.style.display = 'none';
                    packageGrid.innerHTML = '<p style="text-align: center; grid-column: 1 / -1; color: var(--text-light);">暂无推荐套餐，请稍后再试。</p>';
                    console.warn('获取推荐套餐成功但无数据:', result.msg);
                }

            } catch (error) {
                console.error('获取推荐套餐失败:', error);
                recommendationLoading.style.display = 'none';
                packageGrid.innerHTML = `<p style="text-align: center; grid-column: 1 / -1; color: var(--danger);">加载推荐套餐失败：${error.message}，请检查网络或后端服务。</p>`;
                alert('加载推荐套餐失败！');
            } finally {
                refreshRecommendationsBtn.disabled = false; // 重新启用按钮
            }
        }

        // 页面加载完成后首次获取推荐套餐 (此时没有AI advice，会执行默认的随机推荐)
        fetchRecommendedPackages();

        // 换一换按钮事件监听器
        refreshRecommendationsBtn.addEventListener('click', function() {
            // 如果有上次生成的AI建议，就用AI建议去重新获取推荐；否则随机获取
            fetchRecommendedPackages(lastGeneratedAIDesignAdvice);
        });
    });
</script>
</body>
</html>